package cn.fldong.controller;

import cn.fldong.model.User;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 身份验证过滤器，控制用户访问权限
 */
public class AuthFilter implements Filter {
    // 不需要登录即可访问的路径
    private static final String[] EXCLUDE_PATHS = {
        "/login.jsp", "/register.jsp", "/css/", "/js/", "/images/", "/UserServlet?action=login", "/UserServlet?action=logout"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        String requestURI = request.getRequestURI();

        // 检查是否是不需要登录的路径
        if (isExcludedPath(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        // 检查是否有权限访问管理员资源
        if (requestURI.contains("/admin/") && !"admin".equals(user.getRole())) {
            // 无权限，转发到错误页面
            request.setAttribute("errorMsg", "您没有权限访问该资源，请联系管理员");
            request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request, response);
            return;
        }

        // 已登录且有权限，继续访问
        filterChain.doFilter(request, response);
    }

    /**
     * 判断请求路径是否在排除列表中
     */
    private boolean isExcludedPath(String requestURI) {
        for (String path : EXCLUDE_PATHS) {
            if (requestURI.contains(path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        // 销毁操作
    }
}